package com.imooc.oauth2.server.controller;

import com.imooc.commons.model.domain.ResultInfo;
import com.imooc.commons.model.domain.SignInIdentity;
import com.imooc.commons.model.vo.SignInDinerInfo;
import com.imooc.commons.utils.ResultInfoUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

/**
 * 用户中心
 *
 * @author gcq
 * @Create 2022-10-10
 */
@RestController
public class UserController {

    @Resource
    private HttpServletRequest request;

    @Resource
    private RedisTokenStore redisTokenStore;

    /**
     * 两种提交方式
     * 1、localhost:8082/user/me?access_token=57ac22b9-d3af-4359-a2f3-7274abe66fdc
     * 2、Auth -> BannerToken 57ac22b9-d3af-4359-a2f3-7274abe66fdc
     *
     * @param authentication
     * @return
     */
    @GetMapping("user/me")
    public ResultInfo getCurrentUser(Authentication authentication) {
        // 获取登录用户信息，然后设置
        Object signInIdentity = authentication.getPrincipal();
        // 转换为前端可用的视图对象
        SignInDinerInfo signInDinerInfo = new SignInDinerInfo();
        BeanUtils.copyProperties(signInIdentity, signInDinerInfo);
        return ResultInfoUtil.buildSuccess(request.getServletPath(), signInDinerInfo);
    }

    @GetMapping("/user/logout")
    public ResultInfo logOut(String access_token, String authorization) {
        if(StringUtils.isBlank(access_token)) {
            access_token = authorization;
        }
        // 判断 authorization 是否为空
        if(StringUtils.isBlank(access_token)){
            return ResultInfoUtil.buildSuccess(request.getServletPath(), "退出成功");
        }
        if(access_token.toLowerCase().contains("banner ".toLowerCase(Locale.ROOT))){
            access_token = access_token.toLowerCase().replace("banner ".toLowerCase(), " ");
        }
        OAuth2AccessToken oAuth2AccessToken = redisTokenStore.readAccessToken(access_token);
        if(oAuth2AccessToken != null){
            redisTokenStore.removeAccessToken(oAuth2AccessToken);
            OAuth2RefreshToken refreshToken = oAuth2AccessToken.getRefreshToken();
            redisTokenStore.removeRefreshToken(refreshToken);
        }
        return ResultInfoUtil.buildSuccess(request.getServletPath(), "退出成功");
    }
}